﻿namespace JanusLibAing
{

    /// <summary>
    /// Validates data.
    /// XML validation now. We must not allow to send wrong data to the server
    /// </summary>
    public static class Validator
    {

        // valid symbols defined here http://www.w3.org/TR/xml/#charsets
        // Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]	
        /* any Unicode character, excluding the surrogate blocks, FFFE, and FFFF. */

        /// <summary>
        /// Determines whether is symbol is in the specified range.
        /// </summary>
        /// <param name="ch">The test symbol.</param>
        /// <param name="min">The minimum limit.</param>
        /// <param name="max">The maximum limit.</param>
        /// <returns>
        ///     <c>true</c> if the specified symbol in the allowed range; otherwise, <c>false</c>.
        /// </returns>
        public static bool IsSymbolInRange(char ch, char min, char max)
        {
            return ch >= min && ch <= max;
        }

        /// <summary>
        /// Determines whether the specified symbol is valid XML symbol.
        /// </summary>
        /// <param name="ch">The test symbol.</param>
        /// <returns>
        ///     <c>true</c> if the specified symbol is valid XML symbol ; otherwise, <c>false</c>.
        /// </returns>
        public static bool IsValidXMLSymbol(char ch)
        {

            if (IsSymbolInRange(ch, '\x9', '\x9'))
            {
               return true;
            }

            if (IsSymbolInRange(ch, '\xA', '\xA'))
            {
                return true;
            }

            if (IsSymbolInRange(ch, '\xD', '\xD'))
            {
                return true;
            }

            if (IsSymbolInRange(ch, '\x20', '\xD7FF'))
            {
                return true;
            }

            if (IsSymbolInRange(ch, '\xE000', '\xFFFD'))
            {
                return true;
            }

            //if (IsSymbolInRange(ch, (char) 0x10000, '\x10FFFF'))

            //{

            //    return true;

            //}
            return false;
        }

        /// <summary>
        /// Convert the string to 'safe send' form.
        /// </summary>
        /// <param name="input">The input.</param>
        /// <returns></returns>
        public static string ToSafeString(string input)
        {
            char[] charArray = input.ToCharArray();

            for (int i = 0; i < input.Length; i++)
            {
                if (!IsValidXMLSymbol(input[i]))
                {
                    charArray[i] = '*';
                }
            }

            //Encoding encodingUtf8 = Encoding UTF8; 

            input = new string(charArray);

            return input;
        }



 
    }

}


